//
// Created by xiaoqiang on 2023/1/17.
//
#include <curl/curl.h>
#include <memory.h>
#include <stdlib.h>

struct memory {
    char *response;
    size_t size;
};

size_t write_data(void *data, size_t size, size_t nmemb, void *userp)

{

    size_t realsize = size * nmemb;
    struct memory *mem = (struct memory *)userp;

    char *ptr = realloc(mem->response, mem->size + realsize + 1);
    if(ptr == NULL)
        return 0;  /* out of memory! */

    mem->response = ptr;
    memcpy(&(mem->response[mem->size]), data, realsize);
    mem->size += realsize;
    mem->response[mem->size] = 0;

    return realsize;

}
struct memory chunk = {0};

int main(int argc, char *argv[]){
    CURL* pHandle = NULL;
    CURLcode res;
//    char url[128] = "http://ks3-cn-beijing.ksyun.com/live-p2p-resource/Android/P2P/doc/playlist.json";
    char *url = argv[1];
    fprintf(stdout,"%s\n",url);
    pHandle = curl_easy_init();
    if(pHandle != NULL){
        curl_easy_setopt(pHandle,CURLOPT_URL,url);
        curl_easy_setopt(pHandle,CURLOPT_WRITEFUNCTION,write_data);
        curl_easy_setopt(pHandle,CURLOPT_WRITEDATA,&chunk);
//        curl_easy_setopt(pHandle,CURLOPT_VERBOSE,1);
        res = curl_easy_perform(pHandle);
        curl_easy_cleanup(pHandle);
    }

    if(CURLE_OK != res){
        fprintf(stderr,"curl open error %d\n",res);
    }else{
        fprintf(stdout,"%s\n",chunk.response);
    }
//    curl_global_cleanup();
    return 0;
}
